<?php


namespace app\engine\controller;


use cmf\controller\HomeBaseController;
use think\Db;

class ProjectController extends HomeBaseController
{
    public function index()
    {
        $data = $this->request->param();
        $res = Db::name('pay_enter')->where(['eid' => $data['id']])->order('date desc')->select()->toArray();
        $all = Db::name('pay_enter')->where(['eid' => $data['id']])->sum('price');
        $hss = Db::name('engine')->where(['id' => $data['id']])->value('countPrice') - $all;
        $this->assign('hss', $hss);
        $this->assign('all', $all);
        $this->assign('res', $res);
        $this->assign('id', $data['id']);
        return $this->fetch();
    }

    public function add()
    {
        $role = Db::name('role_user')->where(['user_id'=>cmf_get_current_admin_id()])->value('role_id');
        if($role == 2){
            $this->error('无权限操作');
        }
        $data = $this->request->param();
        $this->assign('id', $data['id']);
        return $this->fetch();
    }

    public function doadd()
    {
        $data = $this->request->param();
        if (empty($data['eid'])) {
            $this->error('缺少关键参数 ');
        }
        if (empty($data['date']) || empty($data['pay']) || empty($data['desc']) || empty($data['unit']) || empty($data['price']) || empty($data['title'])) {
            $this->error('请填写完整');
        }
        $check = Db::name('engine')->where(['id' => $data['eid']])->find();
        $data['outsComp'] = $check['unit'];
        $data['insComp'] = $check['Bidder'];
        $files = $this->request->file('img');
        if ($files) {
            $kps = [];
            foreach ($files as $k => $file) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->move(CMF_ROOT . 'public' . '/' . 'uploads');
                if ($info) {
                    $kps[$k] = '/uploads/' . date('Ymd', time()) . '/' . $info->getFilename();
                } else {
                    $this->error($file->getError());
                }
            }
            $data['imgs'] = implode(',', $kps);
        }
        $res = Db::name('pay_enter')->insert($data);
        if (!$res) {
            $this->error('添加失败');
        }
        $this->success('添加成功');
    }

    public function del()
    {
        $role = Db::name('role_user')->where(['user_id'=>cmf_get_current_admin_id()])->value('role_id');
        if($role == 2){
            $this->error('无权限操作');
        }
        $data = $this->request->param();
        $check = Db::name('pay_enter')->where(['id'=>$data['id']])->find();
        if($check['imgs']){
            $img = explode(',',$check['imgs']);
            foreach ($img as $k =>$v){
                $v = CMF_ROOT . $v;
                if(file_exists($v) && $v != CMF_ROOT){
                    unlink($v);
                }
            }
        }
        $res = Db::name('pay_enter')->where(['id' => $data['id']])->delete();
        if (!$res) {
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }

    public function see()
    {
        $data = $this->request->param();
        $res = Db::name('pay_enter')->where(['id' => $data['id']])->find();
        if($res['imgs']){
            $res['imgs'] = explode(',',$res['imgs']);
            foreach ($res['imgs'] as $k => &$v){
                $v = 'http://' . $_SERVER['SERVER_NAME'] . $v;
            }
        }
        $this->assign('res', $res);
        return $this->fetch();
    }

    public function doedit()
    {
        $role = Db::name('role_user')->where(['user_id'=>cmf_get_current_admin_id()])->value('role_id');
        if($role == 2){
            $this->error('无权限操作');
        }
        $data = $this->request->param();
        $files = $this->request->file('img');
        $id = $data['id'];
        unset($data['id']);
        
        // 获取当前图片列表
        $check = Db::name('pay_enter')->where(['id'=>$id])->find();
        $finalImgArray = [];
        
        // 处理要保留的旧图片
        if (isset($data['old_img']) && !empty($data['old_img'])) {
            $oldImages = $data['old_img'];
            unset($data['old_img']);
            
            foreach ($oldImages as $imgUrl) {
                // 从URL中提取路径
                if (strpos($imgUrl, 'http://') === 0 || strpos($imgUrl, 'https://') === 0) {
                    $parsedUrl = parse_url($imgUrl);
                    $finalImgArray[] = $parsedUrl['path'];
                } else {
                    $finalImgArray[] = $imgUrl;
                }
            }
        }
        
        // 处理要删除的图片
        if (isset($data['remove_img']) && !empty($data['remove_img'])) {
            $removeImages = $data['remove_img'];
            unset($data['remove_img']);
            
            foreach ($removeImages as $imgUrl) {
                // 从URL中提取路径
                $imgPath = '';
                if (strpos($imgUrl, 'http://') === 0 || strpos($imgUrl, 'https://') === 0) {
                    $parsedUrl = parse_url($imgUrl);
                    $imgPath = $parsedUrl['path'];
                } else {
                    $imgPath = $imgUrl;
                }
                
                // 删除文件
                $path = CMF_ROOT . 'public' . $imgPath;
                if (file_exists($path)) {
                    unlink($path);
                }
                
                // 从最终图片数组中移除
                $key = array_search($imgPath, $finalImgArray);
                if ($key !== false) {
                    unset($finalImgArray[$key]);
                }
            }
        }
        
        // 处理新上传的图片
        if ($files) {
            foreach ($files as $file) {
                // 为每个文件创建唯一目录
                $uploadDir = 'uploads/' . date('YmdHis') . mt_rand(1000, 9999) . '_' . mt_rand(1000, 9999);
                // 确保目录存在
                if (!file_exists(CMF_ROOT . 'public/' . $uploadDir)) {
                    mkdir(CMF_ROOT . 'public/' . $uploadDir, 0777, true);
                }
                
                // 生成唯一文件名
                $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
                $newFilename = md5(uniqid(mt_rand(), true)) . '.' . $extension;
                
                // 直接使用PHP的move_uploaded_file函数
                $tmpName = $file->getInfo('tmp_name');
                $destPath = CMF_ROOT . 'public/' . $uploadDir . '/' . $newFilename;
                
                if (move_uploaded_file($tmpName, $destPath)) {
                    $finalImgArray[] = '/' . $uploadDir . '/' . $newFilename;
                } else {
                    $this->error('文件上传失败');
                }
            }
        }
        
        // 更新图片字段
        if (!empty($finalImgArray)) {
            $data['imgs'] = implode(',', $finalImgArray);
        } else {
            $data['imgs'] = '';
        }
        
        unset($data['img']);
        
        $res = Db::name('pay_enter')->where(['id' => $id])->update($data);
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }
}